﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
using System.Xml.Serialization;
using SysMisc;


namespace Kernel
{
    /// <summary>
    /// 工程相关操作，包括文件操作
    /// </summary>
    public class Project : IExtensionApplication
    {
        public Project()
        {

        }

        public Project( string fileFullName )
        {
            this._fil_info = new FileInfo(fileFullName);
        }

        public bool IsUpdated { get; set; }//工程是否有更新，标识符
        public SystemConfig SystemConfig { get { return _sys_cfg; } }
        public ProjectConfig ProjectConfig { get { return _prj_cfg; } }
        /// <summary>
        /// 存储工程文件信息“*.spm”
        /// </summary>
        public FileInfo PrjFileInfo{ get { return _fil_info; } }
        public Dictionary<string, OrderTempItem> DicOrderTemplateItem { get; set; }/*图纸排序模板链表*/
        public int ErrorCode { get { return _err_code; } }
        public string ErrorText { get { return _err_text; } }

        private List<Document> _lst_doc = new List<Document>();/*用来保存当前工程所有的已打开的文档*/
        private FileInfo _fil_info = null;
        private SystemConfig _sys_cfg = new SystemConfig();
        private ProjectConfig _prj_cfg = new ProjectConfig();
        private int _err_code = 0;
        private string _err_text = "";
        private xmlCatalogue _CataloguePaper;
        private xmlCatgPaper _CatgPaperCur;/*指向当前读取的目录页的相应的配置文件的参数*/

        public bool OpenAllFilesOfPrj()
        {
            _lst_doc.Clear();
            foreach(xmlFile fil in _prj_cfg.Files)
            {
                Document doc = null;
                string fileFullPath = _fil_info.Directory + @"\" + fil.FileName;
                if ( fil.FileType.Equals(".dwg"))
                {
                    doc = Core.GetDocFromOpenedFiles(fileFullPath);
                    if (null==doc )
                        doc  = Core.OpenDoc(fileFullPath);
                    if (null != doc)
                        _lst_doc.Add(doc);
                    else
                        return false;
                }
            }
            return true;
        }

        public bool LoadSystemConfig()
        {
            SystemConfig sc = SysMisc.Serialization.DeSerializeFromXml<SystemConfig>( Misc.GetAppPath()+ @"\Resources\xml\AppConfig.xml");
            if (null == sc)
                return false;

            this._sys_cfg = sc;
            return true;
        }

        /// <summary>
        /// 更新所有图纸（包括 工程名，阶段，编号，时间）
        /// </summary>
        public void UpdateAllPapers()
        {
            //将 工程名 按照 "," 分割
            string strPrjName, strPrjName0 = "", strPrjName1 = "";
            strPrjName = _prj_cfg.MainCfg.PrjName;
            if (true == strPrjName.Contains(","))
            {
                string[] strs = strPrjName.Split(',');
                strPrjName0 = strs[0];
                strPrjName1 = strs[1];
                strPrjName = "";
            }

            //遍历所有文件
            foreach (xmlFile file in _prj_cfg.Files)
            {
                Document doc;
                string fileFullName = _fil_info.Directory + @"\" + file.FileName;
                FileInfo fil = new FileInfo(fileFullName);
                if (false == fil.Extension.Equals(".dwg"))//如果不是CAD文件，则继续下一个
                    continue;

                doc = Core.GetDocFromOpenedFiles(fileFullName);
                if (null == doc)
                    doc = Core.OpenDoc(fileFullName);
                if (null != doc)
                    _lst_doc.Add(doc);
                else { Misc.Alert(string.Format("找不到文件“{0}”，更新失败！", fil.Name));return; }

                //将所有图纸条目，压入字典
                Dictionary<string, xmlCatalogue> dic_cataItm = new Dictionary<string, xmlCatalogue>();
                foreach (xmlCatalogue itm in _prj_cfg.Catalogues)
                    if (itm.PaperName?.Equals("") == false)
                        dic_cataItm.Add(itm.PaperName, itm);

                //开始轮询文件
                using (Transaction tr = doc.TransactionManager.StartTransaction())
                {
                    List<BlockReference> lst_br =  Common.ListAllBlockReference(doc.Database, OpenMode.ForRead);

                    foreach( BlockReference br in lst_br)
                    {
                        //得到此块的所有属性
                        AttributeCollection att_col = br.AttributeCollection;

                        //先判断此块是否是图框，且不是目录
                        bool isPaper = false;
                        foreach (ObjectId obj_id in att_col)
                        {
                            AttributeReference att_ref = (AttributeReference)tr.GetObject(obj_id, OpenMode.ForWrite);
                            if (att_ref.Tag.Equals("图框名"))
                                if (false == att_ref.TextString.Equals("cat"))
                                {
                                    isPaper = true;
                                    break;
                                }

                        }

                        //如果没找到，说明这不是一个图框，继续搜索下一个块
                        if (false == isPaper)
                            continue;

                        //否则，得到其中的图纸名称,及对应对象
                        string paperName=null;
                        xmlCatalogue catItem = null;
                        foreach (ObjectId obj_id in att_col)
                        {
                            AttributeReference att_ref = (AttributeReference)tr.GetObject(obj_id, OpenMode.ForWrite);

                            if (att_ref.Tag.Equals("DRAW_NAME1"))
                            {
                                paperName = att_ref.TextString;
                                dic_cataItm.TryGetValue(paperName, out catItem);
                                break;//找到了，就跳出循环
                            }

                        }

                        /*判断图纸条目是否为空，为空，就说明这个图纸名可能不参与编号（也可能是因为当前工程，条目没有更新）
                         但是不影响编号，下面的条目继续编号*/
                        if (null == catItem)
                        { continue; }

                        foreach (ObjectId obj_id in att_col)
                        {
                            AttributeReference att_ref = (AttributeReference)tr.GetObject(obj_id, OpenMode.ForWrite);
                            switch (att_ref.Tag)
                            {
                                case "DRAW_NUM":
                                    att_ref.TextString = catItem.PaperCode;
                                    break;
                                case "PROJECT_NAME":
                                    att_ref.TextString = strPrjName;
                                    break;
                                case "PROJECT_NAME0":
                                    att_ref.TextString = strPrjName0;
                                    break;
                                case "PROJECT_NAME1":
                                    att_ref.TextString = strPrjName1;
                                    break;
                                case "STEP":
                                    att_ref.TextString = _prj_cfg.MainCfg.State;
                                    break;
                                case "DRAW_DATE":
                                    att_ref.TextString = _prj_cfg.MainCfg.PubDate;
                                    break;
                            }
                        }
                    }

                    tr.Commit();
                }
            }
        }

        /// <summary>
        /// 更新所有图纸（包括 工程名，阶段，编号，时间）
        /// </summary>
        public void UpdateAllPapers_tmp()
        {
            foreach(xmlCatalogue ctg in _prj_cfg.Catalogues)
            {
                Document doc;
                string fileFullName = _fil_info.Directory + @"\" + ctg.FileName;
                FileInfo fil = new FileInfo(fileFullName);
                if (ctg.FileType.Equals(".dwg"))
                {
                    doc = Core.GetDocFromOpenedFiles(fileFullName);
                    if (null == doc)
                        doc = Core.OpenDoc(fileFullName);
                    if (null != doc)
                        _lst_doc.Add(doc);

                    using (Transaction tr = doc.TransactionManager.StartTransaction())
                    {
#if CAD_2008
                        ObjectId br_obj_id = new ObjectId((int)(ctg.Tag));
#elif CAD_2014
                        ObjectId br_obj_id = new ObjectId((System.IntPtr)(ctg.Tag));
#endif
                        BlockReference blk_ref = (BlockReference)tr.GetObject(br_obj_id, OpenMode.ForWrite);

                        //将 工程名 按照 "," 分割
                        string strPrjName, strPrjName0="", strPrjName1="";
                        strPrjName = _prj_cfg.MainCfg.PrjName;
                        if(true == strPrjName.Contains(","))
                        {
                            string[] strs = strPrjName.Split(',');
                            strPrjName0 = strs[0];
                            strPrjName1 = strs[1];
                        }

                        AttributeCollection att_col = blk_ref.AttributeCollection;
                        foreach (ObjectId obj_id in att_col)
                        {
                            //AttributeReference att_ref = (AttributeReference)obj_id.GetObject(OpenMode.ForRead);
                            AttributeReference att_ref = (AttributeReference)tr.GetObject(obj_id, OpenMode.ForWrite);
                            switch( att_ref.Tag)
                            {
                                case "DRAW_NUM":
                                    att_ref.TextString = ctg.PaperCode;
                                    break;
                                case "PROJECT_NAME":
                                    att_ref.TextString = strPrjName;
                                    break;
                                case "PROJECT_NAME0":
                                    att_ref.TextString = strPrjName0;
                                    break;
                                case "PROJECT_NAME1":
                                    att_ref.TextString = strPrjName1;
                                    break;
                                case "STEP":
                                    att_ref.TextString = _prj_cfg.MainCfg.State;
                                    break;
                                case "DRAW_DATE":
                                    att_ref.TextString = _prj_cfg.MainCfg.PubDate;
                                    break;
                            }
                        }

                        tr.Commit();
                    }
                }
            }
        }

        public bool IsCategoryPaper( string strPaperSpec)
        {
            if (strPaperSpec.IndexOf("cat") >= 0)
                return true;
            else
                return false;
        } 
        /// <summary>
        /// 首先确认工程里是否有目录项
        /// </summary>
        /// <returns></returns>
        public bool IsCategoryPaperExistCatalogueConfig()
        {
            bool isFinded = false;
            foreach (xmlCatalogue cat in _prj_cfg.Catalogues)
            {
                //轮询当前系统配置中，所有的目录页
                foreach(xmlCatgPaper cp in _sys_cfg.CatgPapers)
                {
                    if (cat.PaperSpec.Equals(cp.PaperSpec))
                    {
                        isFinded = true;
                        _CataloguePaper = cat;//设置目录页
                        _CatgPaperCur = cp;//设置当前指向的配置文件中的配置项
                        break;
                    }

                }
            }

            return isFinded;
        }

        /// <summary>
        /// 通过块名，来找到块实例，通常是为了找到目录页
        /// </summary>
        /// <param name="strSpecName"></param>
        /// <returns></returns>
        public BlockReference GetBlockRefByBlockSpec(Document doc ,string strSpecName  )
        {
            using (Transaction tr = doc.TransactionManager.StartTransaction())
            {
                List<BlockReference> lst_br = Common.ListAllBlockReference(doc.Database, OpenMode.ForRead);

                foreach (BlockReference br in lst_br)
                {
                    DynamicBlockReferencePropertyCollection col_dbrp = br.DynamicBlockReferencePropertyCollection;

                    foreach (ObjectId att_id in br.AttributeCollection)
                    {
                        AttributeReference ar = tr.GetObject(att_id, OpenMode.ForRead) as AttributeReference;
                        //Misc.WriteToTxtFile(string.Format("---AttTag:{0}  AttText:{1}\r\n", ar.Tag, ar.TextString));
                        if ((ar.Tag.Equals("图框名")) && (ar.TextString.Equals(strSpecName)))
                        {
                            tr.Commit();
                            return br;
                        }
                    }
                }

                tr.Commit();
            }
            return null;
        }

        /// <summary>
        /// 填充目录
        /// </summary>
        public void FillCategoryPaperItems()
        {
            double x_base = 95.1794, y_base = -418.8695;
            double p1_r1_y_off = 206;//首行目录条目的y偏移
            double p1_v1_x_off = 28;//首列目录条目的x偏移
            double p1_v2_x_off = 36;//2列目录条目的x偏移
            double p1_v3_x_off = 83;//3列目录条目的x偏移
            double p1_v4_x_off = 158;//4列目录条目的x偏移

            int rows_max = 24;
            double p1_r_y_off = -8;//目录条目的y偏移
            //string str = "123";

            if( false == IsCategoryPaperExistCatalogueConfig() )
            {
                Misc.Alert("图纸中没有找到目录框。");
                return;
            }

            //判断当前目录，是否能够容下所有条目（这个还是有问题的，因为有些条目，不参与编码）
            if( _CatgPaperCur.MaxItemCount < _prj_cfg.Catalogues.Count + _prj_cfg.MainCfg.StartNum )
            {
                Misc.Alert(string.Format("当前找到的图纸目录页中没有足够的框格，能够容下所有的图纸条目，点击确定返回。\r\n目录最多容纳：{0}条；共有条目：{1}条；编号起始条目：{2}条；全部条目：{3}条；", _CatgPaperCur.MaxItemCount, _prj_cfg.Catalogues.Count,_prj_cfg.MainCfg.StartNum, _prj_cfg.Catalogues.Count+_prj_cfg.MainCfg.StartNum));
                return;
            }

            //填充目录页页头
            funcFillCategoryPaperHeader();

            //填充目录页条目
            Document doc = Core.GetDoc( _fil_info.Directory+@"\"+ _CataloguePaper.FileName);
            Point3d pt_base = GetBlockRefByBlockSpec(doc,_CataloguePaper.PaperSpec).Position;
            x_base = pt_base.X;y_base = pt_base.Y;
            p1_r1_y_off = _CatgPaperCur.CatgPages[0].Offset_Y1;
            p1_v1_x_off = _CatgPaperCur.CatgPages[0].Offset_X1;
            p1_v2_x_off = _CatgPaperCur.CatgPages[0].Offset_X2;
            p1_v3_x_off = _CatgPaperCur.CatgPages[0].Offset_X3;
            p1_v4_x_off = _CatgPaperCur.CatgPages[0].Offset_X4;

            using (Transaction tr = doc.TransactionManager.StartTransaction())
            {
                //for ( int i = 0; i < rows_max; i++)
                int p = 0;//当前录入的是目录的第p页
                int n = 0;//当前录入目录条目总和
                int i = 0;//目录的当前页，录入的条目数量

                //更新p,n,i,及相关偏移值
                {

                    if (_prj_cfg.MainCfg.StartNum > 0)
                    {
                        n = _prj_cfg.MainCfg.StartNum-1;
                        i = n;
                    }

                    while ( i> _CatgPaperCur.CatgPages[p].MaxItemCount)
                    {
                        i -= _CatgPaperCur.CatgPages[p].MaxItemCount;
                        p++;
                    }

                    p1_r1_y_off = _CatgPaperCur.CatgPages[p].Offset_Y1;
                    p1_v1_x_off = _CatgPaperCur.CatgPages[p].Offset_X1;
                    p1_v2_x_off = _CatgPaperCur.CatgPages[p].Offset_X2;
                    p1_v3_x_off = _CatgPaperCur.CatgPages[p].Offset_X3;
                    p1_v4_x_off = _CatgPaperCur.CatgPages[p].Offset_X4;
                }


                foreach (xmlCatalogue cat in _prj_cfg.Catalogues)
                {
                    //如果此条目不编码，则跳到下一条目
                    if (true == cat.IsNoNum) { continue; }

                    Point3d pt = new Point3d(1, 1, 1);
                    DBText db_txt = null;
                    //序号
                    pt = new Point3d((x_base + p1_v1_x_off), (y_base + p1_r1_y_off + p1_r_y_off * i), 0);
                    db_txt = Common.NewDBText((n + 1).ToString(), pt, 4, 0, false);
                    Core.AppendToModelSpace(db_txt, doc.Database);
                    //编号
                    pt = new Point3d((x_base + p1_v2_x_off), (y_base + p1_r1_y_off + p1_r_y_off * i), 0);
                    db_txt = Common.NewDBText(cat.PaperCode, pt, 4, 0, false);
                    Core.AppendToModelSpace(db_txt, doc.Database);
                    //名称
                    pt = new Point3d((x_base + p1_v3_x_off), (y_base + p1_r1_y_off + p1_r_y_off * i), 0);
                    db_txt = Common.NewDBText(cat.PaperName, pt, 4, 0, false);
                    Core.AppendToModelSpace(db_txt, doc.Database);
                    //份数
                    pt = new Point3d((x_base + p1_v4_x_off), (y_base + p1_r1_y_off + p1_r_y_off * i), 0);
                    db_txt = Common.NewDBText(cat.PaperCount, pt, 4, 0, false);
                    Core.AppendToModelSpace(db_txt, doc.Database);

                    //移至下一行
                    n++;
                    i++;

                    //此逻辑用来判断是否需要翻页等操作
                    if (i >= _CatgPaperCur.CatgPages[p].MaxItemCount)
                    {//此页已录完，需要翻页
                        //进行翻页的数据初始化
                        p++;
                        i = 0;

                        p1_r1_y_off = _CatgPaperCur.CatgPages[p].Offset_Y1;
                        p1_v1_x_off = _CatgPaperCur.CatgPages[p].Offset_X1;
                        p1_v2_x_off = _CatgPaperCur.CatgPages[p].Offset_X2;
                        p1_v3_x_off = _CatgPaperCur.CatgPages[p].Offset_X3;
                        p1_v4_x_off = _CatgPaperCur.CatgPages[p].Offset_X4;
                    }
                }

                //确认修改
                tr.Commit();

            }
        }

        //填充目录页的页头
        private void funcFillCategoryPaperHeader()
        {
            Document doc = Core.GetDoc(_fil_info.Directory + @"\" + _CataloguePaper.FileName);
            BlockReference br_catg = GetBlockRefByBlockSpec(doc, _CataloguePaper.PaperSpec);//得到目录页

            using (Transaction tr = doc.TransactionManager.StartTransaction())
            {
                //得到块的属性集
                AttributeCollection att_col = br_catg.AttributeCollection;
                foreach (ObjectId obj_id in att_col)
                {
                    AttributeReference att_ref = (AttributeReference)tr.GetObject(obj_id, OpenMode.ForWrite);
                    switch( att_ref.Tag)
                    {
                        case "PROJECT_NAME"://工程名称
                            if (_prj_cfg.MainCfg.PrjName.Contains(",") == false)
                                att_ref.TextString = _prj_cfg.MainCfg.PrjName;
                            else
                                att_ref.TextString = "";
                            //att_ref.TextString = _prj_cfg.MainCfg.PrjName.Replace(",", "");
                            break;
                        case "PROJECT_NAME0"://工程名称0
                            if (_prj_cfg.MainCfg.PrjName.Contains(",") == true)
                                att_ref.TextString = _prj_cfg.MainCfg.PrjName.Split(',')[0];
                            else
                                att_ref.TextString = "";
                            break;
                        case "PROJECT_NAME1"://工程名称1
                            if (_prj_cfg.MainCfg.PrjName.Contains(",") == true)
                                att_ref.TextString = _prj_cfg.MainCfg.PrjName.Split(',')[1];
                            else
                                att_ref.TextString = "";
                            break;
                        case "DRAW_NUM"://卷册检索号
                            att_ref.TextString = _prj_cfg.MainCfg.CmpyCode + "-"+  _prj_cfg.MainCfg.PrjCode;
                            break;
                        case "STEP"://设计阶段
                            att_ref.TextString = _prj_cfg.MainCfg.State;
                            break;
                        case "ZHUANYE"://部分
                            att_ref.TextString = _prj_cfg.MainCfg.Subject;
                            break;
                        case "VOLUMENUMBER"://卷数-第几卷
                            if(_prj_cfg.MainCfg.VolNum>0)
                                att_ref.TextString = _prj_cfg.MainCfg.VolNum.ToString();
                            break;
                        case "BOOKCOUNT"://册数-第几册
                            if (_prj_cfg.MainCfg.VolNum > 0)
                                att_ref.TextString = _prj_cfg.MainCfg.RowNum.ToString();
                            break;
                        case "DRAW_NAME"://卷册名称
                            att_ref.TextString = _prj_cfg.MainCfg.VolName;
                            break;
                        case "DRAWINGCOUNT"://图纸-张数
                            att_ref.TextString = _prj_cfg.Catalogues.FindAll(x=>(x.PaperCount.Equals("1") && x.IsNoNum==false)).Count.ToString();
                            break;
                        case "DRAWINGBOOKCOUNT"://图纸-本数
                            break;
                        case "MANUALCOUNT"://说明书数
                            break;
                        case "DRAW_DATE"://日期
                            att_ref.TextString = _prj_cfg.MainCfg.PubDate;
                            break;
                        case "BARCODE"://条形码
                            break;
                        case "DRAW_NUM2"://卷册检索号-第二列
                            att_ref.TextString = _prj_cfg.MainCfg.CmpyCode + "-" + _prj_cfg.MainCfg.PrjCode;
                            break;
                    }
                }

                //确认修改
                tr.Commit();
            }
        }

        /// <summary>
        /// 填充目录
        /// </summary>
        public void FillCategoryPaperItems_tmp()
        {
            double x_base = 95.1794, y_base = -418.8695;
            double p1_r1_y_off = 206;//首行目录条目的y偏移
            double p1_v1_x_off = 28;//首列目录条目的x偏移
            double p1_v2_x_off = 36;//2列目录条目的x偏移
            double p1_v3_x_off = 83;//3列目录条目的x偏移
            double p1_v4_x_off = 158;//4列目录条目的x偏移

            int rows_max = 24;
            double p1_r_y_off = -8;//目录条目的y偏移
            //string str = "123";

            Document doc = Core.GetCurrentActiveDoc();
            //lst_br.AddRange(Common.ListAllBlockReference(doc.Database));
            //List<BlockReference> lst_br = Common.ListAllBlockReference(doc.Database);

            using (Transaction tr = doc.TransactionManager.StartTransaction())
            {
                //for ( int i = 0; i < rows_max; i++)
                int i = 0;
                if (_prj_cfg.MainCfg.StartNum > 0)
                    i = _prj_cfg.MainCfg.StartNum-1;
                else
                    i = 0;
                foreach(xmlCatalogue cat in _prj_cfg.Catalogues )
                {
                    //如果此条目不编码，则跳到下一条目
                    if( true == cat.IsNoNum) { continue; }

                    Point3d pt = new Point3d(1,1,1);
                    DBText db_txt = null;
                    //序号
                    pt = new Point3d((x_base+ p1_v1_x_off), (y_base + p1_r1_y_off + p1_r_y_off * i), 0);
                    db_txt = Common.NewDBText((i+1).ToString(), pt, 4, 0, false);
                    Core.AppendToModelSpace(db_txt, doc.Database);
                    //编号
                    pt = new Point3d((x_base + p1_v2_x_off), (y_base + p1_r1_y_off + p1_r_y_off * i), 0);
                    db_txt = Common.NewDBText(cat.PaperCode, pt, 4, 0, false);
                    Core.AppendToModelSpace(db_txt, doc.Database);
                    //名称
                    pt = new Point3d((x_base + p1_v3_x_off), (y_base + p1_r1_y_off + p1_r_y_off * i), 0);
                    db_txt = Common.NewDBText(cat.PaperName, pt, 4, 0, false);
                    Core.AppendToModelSpace(db_txt, doc.Database);
                    //份数
                    pt = new Point3d((x_base + p1_v4_x_off), (y_base + p1_r1_y_off + p1_r_y_off * i), 0);
                    db_txt = Common.NewDBText("1", pt, 4, 0, false);
                    Core.AppendToModelSpace(db_txt, doc.Database);

                    //移至下一行
                    i++;
                }

                tr.Commit();

            }
        }

        /// <summary>
        /// 得到所有图纸名称
        /// </summary>
        /// <returns></returns>
        public List<xmlCatalogue> GetAllPaperNames()
        {
            List<xmlCatalogue> lst_xmlCtg = new List<xmlCatalogue>();
            //List<BlockReference> lst_br = new List<BlockReference>();
            foreach( Document doc in _lst_doc)
            {
                //lst_br.AddRange(Common.ListAllBlockReference(doc.Database));
                List<BlockReference> lst_br = Common.ListAllBlockReference(doc.Database,OpenMode.ForRead);

                using (Transaction tr = doc.TransactionManager.StartTransaction())
                {
                    foreach (BlockReference blk_ref in lst_br)
                    {
                        bool isFinded = false;
                        AttributeCollection att_col = blk_ref.AttributeCollection;
                        //先寻找块中是否有图框名，这个属性
                        foreach (ObjectId obj_id in att_col)
                        {
                            //AttributeReference att_ref = (AttributeReference)obj_id.GetObject(OpenMode.ForRead);
                            AttributeReference att_ref = (AttributeReference)tr.GetObject(obj_id, OpenMode.ForRead);
                            if (att_ref.Tag.Equals("图框名"))
                            {
                                isFinded = true;
                                break;
                            }

                        }
                        //如果找到，则轮询读取所有属性
                        if(isFinded == true)
                        {
                            xmlCatalogue ctg = new xmlCatalogue();
                            ctg.PaperCode = "N/A";
                            ctg.PaperCount = "1";
                            ctg.FileName = Common.GetDocName(doc);
                            ctg.FileType = Common.GetDocType(doc);
                            //ctg.PaperSpec = blk_ref.Name;
                            ctg.Tag = blk_ref.ObjectId.OldId;
                            foreach (ObjectId obj_id in att_col)
                            {
                                //AttributeReference att_ref = (AttributeReference)obj_id.GetObject(OpenMode.ForRead);
                                AttributeReference att_ref = (AttributeReference)tr.GetObject(obj_id, OpenMode.ForRead);
                                switch(att_ref.Tag)
                                {
                                    case "图框名":
                                    {
                                        ctg.PaperSpec = att_ref.TextString;
                                        if (IsCategoryPaper(ctg.PaperSpec) == true)
                                            ctg.IsNoNum = true;
                                    }
                                    break;
                                    case "DRAW_NAME1":
                                    {
                                        ctg.PaperName = att_ref.TextString;
                                    }
                                    break;
                                }
                           
                            }
                            lst_xmlCtg.Add(ctg);
                        }
                    }
                    tr.Commit();
                }

            }

            _prj_cfg.Catalogues = lst_xmlCtg;
            return lst_xmlCtg;
        }

        /// <summary>
        /// 对图纸进行重新排序
        /// </summary>
        public void ReOrderAllPapers()
        {
            //先根据字典更新权值（默认值-1）
            foreach( xmlCatalogue ctg in _prj_cfg.Catalogues)
            {
                //该条目必须参与排序
                if (ctg.IsNoNum == false)
                {
                    //它的图纸名称不能为空，然后去字典中找它的排序权值
                    if ((ctg.PaperName != null) && (DicOrderTemplateItem.ContainsKey(ctg.PaperName)))
                    {
                        ctg.OrderSeed = DicOrderTemplateItem[ctg.PaperName].PaperPower;
                    }
                }
            }

            //进行排序
            _prj_cfg.Catalogues.Sort();
        }

        /// <summary>
        /// 重新创建图纸目录
        /// </summary>
        public void ReCreateAllPaperCode()
        {
            int n = _prj_cfg.MainCfg.StartNum;
            foreach( xmlCatalogue ctg in _prj_cfg.Catalogues)
            {
                if(ctg.IsNoNum == false )
                    ctg.PaperCode = string.Format("{0}-{1:00}", _prj_cfg.MainCfg.PrjCode, n++);
            }
        }


        public bool TryToOpenPrjFileByFileFullPath( string fileFullPath )
        {
            _prj_cfg = SysMisc.Serialization.DeSerializeFromXml<ProjectConfig>(fileFullPath);
            if (null != _prj_cfg)
            {
                _fil_info = new FileInfo(fileFullPath);
                return true;/*读取工程文件成功*/
            }
            else
                return false;
        }

        /// <summary>
        /// 尝试打开当前活动文档下的工程文件
        /// </summary>
        public bool TryToOpenPrjFileOfActDoc()
        {
            string filName = null;
            DirectoryInfo di = new DirectoryInfo(Common.GetCurrentActiveDocPath());
            FileInfo[] fis = di.GetFiles();
            foreach (FileInfo fi in fis)
            {
                if (fi.Extension.Equals(".spm"))
                {
                    filName = fi.FullName;
                    break;
                }
            }
            if (null != filName)
            {
                _prj_cfg = SysMisc.Serialization.DeSerializeFromXml<ProjectConfig>(filName);
                if (null != _prj_cfg)
                {
                    _fil_info = new FileInfo(filName);
                    return true;/*读取当前文件下工程文件成功*/
                }
            }
            return false;
        }

        public bool Save()
        {
            SysMisc.Serialization.SerializeToXml<ProjectConfig>(_prj_cfg, _fil_info.FullName);
            return true;
        }

#region 实现IExtensionApplication接口
        public void Initialize()
        {
            //程序加载后，立即执行的代码
        }

        public void Terminate()
        {
        }
#endregion
    }

}
